package com.itheima.controller;

import com.itheima.anno.Log;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/emps")
public class EmpController {

    @Autowired
    private EmpService empService;

    @GetMapping()
    public Result page(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer pageSize) {
        PageBean pageBean = empService.page(page,pageSize);
        return Result.success(pageBean);
    }
    @Log
    @PostMapping
    public Result add(@RequestBody Emp emp) {
        log.info("emp:{}",emp);
        //添加员工之前先判断该员工是否存在，名字有可能相同，以联系电话为唯一标识
        boolean isExit = empService.findByPhone(emp.getPhone());
        if(isExit) {
            return Result.error("该手机号码已经注册过！");
        }
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        empService.add(emp);
        return Result.success();
    }
    @Log
    @PutMapping
    public Result update(@RequestBody Emp emp) {
        //更新之前先根据id判断该员工是否存在
        boolean isExit = empService.findById(emp.getId());
        if(!isExit) {
            return Result.error("该员工不存在");
        }
        emp.setUpdateTime(LocalDateTime.now());
        empService.update(emp);
        return Result.success();
    }

    @Log
    @DeleteMapping
    public Result delete(Integer id) {
        //删除之前先判断该员工是否存在
        boolean isExit = empService.findById(id);
        if(!isExit) {
            return Result.error("该员工不存在");
        }
        empService.delete(id);

        return Result.success();
    }

    /**
     *  批量删除
     * @param ids
     * @return
     */
    @Log
    @DeleteMapping("/{ids}")
    public Result deletes(@PathVariable List<Integer> ids) {
        empService.deletes(ids);
        return Result.success();
    }
}
